package com.my.main.component.interceptor;

import com.my.main.base.entity.response.ProfileResult;
import com.my.main.component.SpringUtil;
import com.my.main.common.utils.IdWorker;
import com.my.main.entity.sysConfig.SysAuditLog;
import com.my.main.service.sysConfig.SysAuditLogService;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.*;


@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })

public class SqlInterceptor implements Interceptor {

//    @Autowired
//    HttpServletRequest request;

    public ProfileResult user;

    private static final Logger logger = LoggerFactory.getLogger(SqlInterceptor.class);
    Properties properties = null;



    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        // 获取 SysAuditLogService 实例
        SysAuditLogService sysAuditLogService = (SysAuditLogService) SpringUtil.getBean("sysAuditLogServiceImpl");
        // 获取id 生成器
        IdWorker idWorker = (IdWorker)SpringUtil.getBean("idWorker");
        // 创建日志实体类
        SysAuditLog sysAuditLog = new SysAuditLog();
        // id
        sysAuditLog.setLogId(idWorker.nextId() + "");

        // 1.获取shiro中的安全数据
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if(principals != null && !principals.isEmpty()){
            this.user  = (ProfileResult)principals.getPrimaryPrincipal();
        }

        Object[] args = invocation.getArgs();

        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        Configuration configuration = mappedStatement.getConfiguration();
        // 获取sql语句
        String sql = showSql(configuration, boundSql);
        sql = sql.replaceAll("\'", "").replace("\"", "");
        String splod = sql.toLowerCase().replace("call", "");
        logger.info(splod);

        // 通过 Sql 截取到属性名 与 属性值


        if(splod.indexOf("sys_audit_log") == -1){
            logger.info(splod.indexOf("update") + "----");

            if (splod.indexOf("update") > -1) {
                System.out.println("update------------------------------------------");
                sysAuditLog.setEventName("事务");
                sysAuditLog.setType("update");
                sysAuditLog.setSessionId(ContextInfo.get("sessionId"));
                sysAuditLog.setLogIp(ContextInfo.get("ip"));
                sysAuditLog.setEventPath(ContextInfo.get("uri"));
                sysAuditLog.setEntityName(args[1].getClass().getSimpleName());
                // 属性名集合
                Field[] field = args[1].getClass().getDeclaredFields();
                List list = new ArrayList<>();
                int count = 0;
                for (Field item : field) {
                    System.out.println(item);

                    list.add(item.getName());
                }
                sysAuditLog.setNames(list.toString());
                sysAuditLog.setCurValues(args[1].toString());

                sysAuditLog.setLogUserId(user == null ? null : user.getUserId());
                sysAuditLog.setLogUserName(user == null ? null : user.getUsername());
                // 新增日志记录
                try {
                    sysAuditLogService.isSave(sysAuditLog);
                }catch (Exception e) {
                    logger.error("新增日志失败");
                }


            } else if (splod.indexOf("insert") > -1) {
                System.out.println("insert------------------------------------------");
                sysAuditLog.setEventName("事务");
                sysAuditLog.setType("insert");
                sysAuditLog.setSessionId(ContextInfo.get("sessionId"));
                sysAuditLog.setLogIp(ContextInfo.get("ip"));
                sysAuditLog.setEventPath(ContextInfo.get("uri"));
                sysAuditLog.setEntityName(args[1].getClass().getSimpleName());
                // 属性名集合
                Field[] field = args[1].getClass().getDeclaredFields();
                List list = new ArrayList<>();
                int count = 0;
                for (Field item : field) {
                    System.out.println(item);

                    list.add(item.getName());
                }
                sysAuditLog.setNames(list.toString());
                sysAuditLog.setCurValues(args[1].toString());

                sysAuditLog.setLogUserId(user == null ? null : user.getUserId());
                sysAuditLog.setLogUserName(user == null ? null : user.getUsername());
                // 新增日志记录
                try {
                    sysAuditLogService.isSave(sysAuditLog);
                }catch (Exception e) {
                    logger.error("新增日志失败");
                }
            } else if (splod.indexOf("delete") > -1) {
                System.out.println("delete------------------------------------------");
                sysAuditLog.setEventName("事务");
                sysAuditLog.setType("delete");
                sysAuditLog.setSessionId(ContextInfo.get("sessionId"));
                sysAuditLog.setLogIp(ContextInfo.get("ip"));
                sysAuditLog.setEventPath(ContextInfo.get("uri"));
                sysAuditLog.setEntityName(args[1].getClass().getSimpleName());
                // 属性名集合
                Field[] field = args[1].getClass().getDeclaredFields();
                List list = new ArrayList<>();
                int count = 0;
                for (Field item : field) {
                    System.out.println(item);

                    list.add(item.getName());
                }
                sysAuditLog.setNames(list.toString());
                sysAuditLog.setCurValues(args[1].toString());

                sysAuditLog.setLogUserId(user.getUserId());
                sysAuditLog.setLogUserName(user.getUsername());
                // 新增日志记录
                try {
                    sysAuditLogService.isSave(sysAuditLog);
                }catch (Exception e) {
                    logger.error("新增日志失败");
                }

            }
        }

        // 执行结果
        Object returnValue = null;
        returnValue = invocation.proceed();
        return returnValue;
    }

    @Override
    public Object plugin(Object target) {
        System.out.println(target);
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        //赋值成员变量，在其他方法使用。
        this.properties = properties;
    }

    public String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

    private String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

}
